package com.haolp.sys.controller;

import com.haolp.sys.common.vo.JsonResultVO;
import com.haolp.sys.dao.SysUserRoleDao;
import com.haolp.sys.pojo.SysUser;
import com.haolp.sys.service.SysUserService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 小李
 * @version 1.0
 * @date 2021/10/12 14:19
 */
@RestController
@RequestMapping("/user/")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @RequestMapping("doUpdatePassword")
    public JsonResultVO doUpdatePassword(
            String pwd,String newPwd,String cfgPwd){
        sysUserService.updatePassword(pwd, newPwd, cfgPwd);
        return new JsonResultVO("修改成功");
    }

    @RequestMapping("doLogin")
    public JsonResultVO doLogin(String username, String password,
                                boolean isRememberMe){
        //1.获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.通过Subject提交用户信息，交给shiro框架进行认证操作
        UsernamePasswordToken token=new UsernamePasswordToken(username,password);
        if (isRememberMe){
            token.setRememberMe(true);
        }
        //2.2对用户信息进行认证
        subject.login(token);
        /**分析：
         * 1)token会传给shiro的SecurityManager
         * 2)SecurityManager将token传递给认证管理器
         * 3)认证管理器会将token传递给realm
         */
        return new JsonResultVO("login ok");
    }

    @RequestMapping("doUpdateObject")
    public JsonResultVO doUpdateObject(SysUser entity, Integer[] roleIds) {
        sysUserService.updateObject(entity, roleIds);
        return new JsonResultVO("update ok");
    }

    @RequestMapping("doFindObjectById")
    public JsonResultVO doFindObjectById(@RequestParam("id") Integer userId) {
        return new JsonResultVO(sysUserService.findObjectById(userId));
    }

    @RequestMapping("doSaveObject")
    public JsonResultVO doSaveObject(SysUser sysUser, Integer[] roleIds) {
        sysUserService.saveObject(sysUser, roleIds);
        return new JsonResultVO("save ok");
    }

    @RequestMapping("doValidById")
    public JsonResultVO doValidById(Integer id, Integer valid) {
        sysUserService.validById(id, valid, "admin");
        return new JsonResultVO("update ok");
    }

    @RequestMapping("doFindPageObjects")
    public JsonResultVO doFindPageObjects(String username, Integer pageCurrent) {
        return new JsonResultVO
                (sysUserService.findPageObjects(username, pageCurrent));
    }
}
